<template>
  <div class="app-container">
    <!--    表单查询区-->
    <div class="filter-container">
      <el-input v-model="listQuery.key" placeholder="管理员名" style="width: 200px; margin-right: 10px" class="filter-item" clearable @keyup.enter.native="handleFilter" @clear="handleFilter" />
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        搜索
      </el-button>
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleCreate">
        添加
      </el-button>
      <el-button v-waves :loading="downloadLoading" class="filter-item" type="primary" icon="el-icon-download" @click="handleDownload">
        批量导出
      </el-button>
    </div>

    <!--表格区-->
    <el-table
      v-loading="listLoading"
      :data="list"
      row-key="id"
      border
      fit
      highlight-current-row
      style="width: 100%;"
    >
      <el-table-column
        label="ID"
        prop="id"
        align="center"
        width="80"
      />
      <el-table-column label="姓名" prop="realName" align="center" />
      <el-table-column label="手机号" prop="phone" align="center" width="150px" />
      <el-table-column label="简介" prop="introduction" align="center" />
      <el-table-column label="操作" align="center" width="150" class-name="small-padding fixed-width">
        <template v-slot="{row}">
          <el-button type="primary" size="mini" @click="handleUpdate(row)">
            编辑
          </el-button>
          <el-button size="mini" type="danger" @click="handleDelete(row)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!--分页插件-->
    <pagination v-show="total>0" :total="total" :page.sync="listQuery.current" :limit.sync="listQuery.size" @pagination="getList" />

    <!--添加、编辑权限对话框-->
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" width="350px">
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="temp"
        label-position="left"
        label-width="65px"
        size="medium"
        @submit.native.prevent
      >
        <el-form-item label="姓名" prop="realName">
          <el-input v-model="temp.realName" type="text" placeholder="姓名" clearable />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="temp.phone" type="text" placeholder="手机号" clearable />
        </el-form-item>
        <el-form-item label="简介" prop="introduction">
          <el-input v-model="temp.introduction" type="textarea" :autosize="{ minRows: 2 }" placeholder="简介" clearable />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          继续
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import waves from '@/directive/waves' // waves directive
import Pagination from '@/components/Pagination'
import { parseTime } from '@/utils'
import { createAdmin, deleteAdminById, getAdminList, getAdminPage, updateAdmin } from '@/api/admin'

export default {
  name: 'Admin',
  components: { Pagination },
  directives: { waves },
  data() {
    // 验证手机号码的规则
    const checkMobile = (rule, value, cb) => {
      // 验证手机号码的正则表达式
      const regMobile = /^1(3[0-9]|4[5,7]|5[012356789]|6[2567]|7[0,178]|8[0-9]|9[189])\d{8}$/
      if (regMobile.test(value) || value === '') {
        return cb()
      }
      cb(new Error('请输入合法的手机号'))
    }

    return {
      // 管理员列表
      list: [],
      // 总数
      total: 0,
      // 表格渲染标志
      listLoading: true,
      // 查询对象
      listQuery: {
        current: 1,
        size: 20,
        key: '',
        roleId: 1001
      },
      // 表单数据
      temp: {
        realName: '',
        phone: '',
        introduction: '',
        roleId: 1001
      },
      // 表单对话框状态控制 true显示  false隐藏
      dialogFormVisible: false,
      // 对话框模式 Create添加 Edit编辑
      dialogStatus: '',
      textMap: {
        update: '编辑管理员',
        create: '添加管理员'
      },
      rules: {
        realName: [{
          required: true,
          message: '管理员姓名不能为空',
          trigger: 'blur'
        }],
        phone: [{
          required: true,
          message: '手机号不能为空',
          trigger: 'blur'
        }, {
          validator: checkMobile,
          trigger: 'change'
        }]
      },
      downloadLoading: false
    }
  },
  created() {
    this.getList()
  },
  methods: {
    // 分页获取管理员列表
    getList() {
      // 开启加载渲染
      this.listLoading = true
      getAdminPage(this.listQuery).then(res => {
        this.list = res.data.records
        this.total = res.data.total
        // 关闭加载渲染
        this.listLoading = false
      }).catch(() => {
        // 请求错误，关闭加载渲染
        this.listLoading = false
      })
    },
    // 搜索处理函数
    handleFilter() {
      this.listQuery.current = 1
      this.getList()
    },
    // 表单重置
    resetTemp() {
      this.temp = {
        realName: '',
        phone: '',
        introduction: '',
        roleId: 1001
      }
    },
    // 添加管理员
    handleCreate() {
      // 重置表单
      this.resetTemp()
      // 创建对话框
      this.dialogStatus = 'create'
      // 显示对话框
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    // 添加管理员
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          createAdmin(this.temp).then(res => {
            this.dialogFormVisible = false
            this.getList()
            this.$notify({
              title: '成功',
              message: res.msg,
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    // 监听更新按钮操作
    handleUpdate(row) {
      this.temp = Object.assign({}, row) // copy obj
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    // 更新管理员
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          updateAdmin(tempData).then(res => {
            this.dialogFormVisible = false
            this.getList()
            this.$notify({
              title: '成功',
              message: res.msg,
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    // 确认删除弹框
    handleDelete(row) {
      this.$confirm('此操作将永久删除, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.deleteData(row)
      }).catch(() => {
        this.$notify({
          title: '提示',
          message: '已取消删除',
          type: 'info',
          duration: 2000
        })
      })
    },
    // 删除管理员
    deleteData(row) {
      deleteAdminById(row.id).then(res => {
        this.getList()
        this.$notify({
          title: '成功',
          message: res.msg,
          type: 'success',
          duration: 2000
        })
      })
    },
    // 下载管理员信息
    handleDownload() {
      this.downloadLoading = true
      getAdminList().then(res => {
        import('@/vendor/Export2Excel').then(excel => {
          const tHeader = ['序号', '姓名', '手机号', '简介', '创建时间', '更新时间']
          const filterVal = ['id', 'realName', 'phone', 'introduction', 'createTime', 'updateTime']
          const data = this.formatJson(filterVal, res.data)
          excel.export_json_to_excel({
            header: tHeader,
            data,
            filename: '管理员列表' + parseTime(new Date(), '{y}-{m}-{d}-{h}-{i}-{s}')
          })
          this.downloadLoading = false
        })
      })
    },
    // 格式化下载数据
    formatJson(filterVal, list) {
      return list.map(v => filterVal.map(j => {
        if (j === 'createTime' || j === 'updateTime') {
          return parseTime(v[j])
        } else {
          return v[j]
        }
      }))
    }
  }
}
</script>

<style scoped>

</style>
